package com.tjhk.netty.mapping;

import com.tjhk.netty.mapping.annotation.Mapping;
import com.tjhk.netty.mapping.handler.SimpleHandler;
import com.tjhk.netty.mapping.handler.Handler;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Map;

/**
 * 消息映射HandlerMapping方法注册
 */
public abstract class AbstractHandlerRegister implements HandlerMapping{
    /**
     * 限制 只可使用一种协议
     */
    private final Map<Object, Handler> handlerMap = new HashMap(60);

    /**
     * 将Endpoint中被@Mapping标记的方法注册到映射表
     */
    protected synchronized void registerHandlers(Object bean) {
        Class<?> beanClass = bean.getClass();
        Method[] methods = beanClass.getDeclaredMethods();
        if (methods == null)
            return;
        for (Method method:methods) {
            Mapping mapping = method.getAnnotation(Mapping.class);
            if (mapping != null){
                String desc = mapping.desc();
                int[] types = mapping.types();
                Handler handler;
                handler = new SimpleHandler(bean, method, desc);
                for (int type : types) {
                    handlerMap.put(type, handler);
                }
            }
        }
    }

    /**
     * 根据消息类型获取Handler方法
     * @param messageType
     * @return
     */
    @Override
    public Handler getHandler(Object messageType) {
        return handlerMap.get(messageType);
    }
}
